package com.example.lxc415billiards.controller;

import com.example.lxc415billiards.domain.User;
import com.example.lxc415billiards.service.UserService;
import com.example.lxc415billiards.untils.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户管理-李效丞0415")
public class UserController {

    @Autowired
    private UserService userService;

    // 查询所有用户
    @ApiOperation("获取所有用户信息")
    @GetMapping("/getAllUsers")
    public AjaxResult getUsers() {
        List<User> users = userService.getAllUsers();
        return AjaxResult.success(users);
    }

    // 根据id查询用户
    @ApiOperation("根据用户ID获取用户信息")
    @GetMapping("getUserById/{id}")
    public AjaxResult getUserById(@PathVariable Long id) {
        User user = userService.getUserById(id);
        if (user!= null) {
            return AjaxResult.success(user);
        } else {
            return AjaxResult.error("用户不存在");
        }
    }

    // 根据用户名查询用户
    @ApiOperation("根据用户名获取用户信息")
    @GetMapping("/byUsername")
    public AjaxResult getUserByUserName(@RequestParam String userName) {
        User user = userService.getUserByUserName(userName);
        if (user!= null) {
            return AjaxResult.success(user);
        } else {
            return AjaxResult.error("用户不存在");
        }
    }

    // 新增用户
    @ApiOperation("新增用户")
    @PostMapping("/addUser")
    public AjaxResult addUser(@RequestBody User user) {
        User savedUser = userService.addUser(user);
        return AjaxResult.success(savedUser);
    }

    // 删除用户
    @ApiOperation("根据用户ID删除用户")
    @DeleteMapping("deleteUSerById/{id}")
    public AjaxResult deleteUserById(@PathVariable Long id) {
        userService.deleteUserById(id);
        return AjaxResult.success("删除用户成功");
    }

    // 修改用户
    @ApiOperation("修改用户信息")
    @PutMapping("/updateUser")
    public AjaxResult updateUser(@RequestBody User user) {
        User updatedUser = userService.updateUser(user);
        if (updatedUser!= null) {
            return AjaxResult.success(updatedUser);
        } else {
            return AjaxResult.error("用户不存在");
        }
    }
}
